package com.haiyi.software.app;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.integer;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.app.sdk.AliPay;
import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Result;
import com.alipay.android.msp.Rsa;
import com.google.gson.JsonObject;
import com.haiyi.software.app.basic.ActivityBasicRecharge;
import com.haiyi.software.entity.UserInfo;

public class ActivityRecharge extends ActivityBasicRecharge {

	public static final String TAG = "alipay-sdk";

	private static final int RQF_PAY = 1;

	private static final int RQF_LOGIN = 2;

	private ListView list_gold;

	private TextView textView_myGolds;

	private UserInfo myInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recharge_gold);

		initView();

		initData();

		requestNetworkData();
	}

	private void initData() {

		myInfo = MainApplication.getInstance().getMineUserInfo();

		this.textView_myGolds.setText(String.valueOf(myInfo.getGold()));
	}

	private void initView() {

		this.list_gold = (ListView) this.findViewById(R.id.list_golds);

		this.textView_myGolds = (TextView) this
				.findViewById(R.id.textView_myGolds);
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO 自动生成的方法存根
			// requestNetworkData(editx_rechargeMoney.getText().toString().trim());

			String str_money = v.getTag().toString();

			String str_gold = String.valueOf(Integer.parseInt(str_money) * 10);

			String str_subject = "充值Hi币_金额:" + str_money + "元_所得Hi币:"
					+ str_gold + "个_@" + myInfo.getUid();

			Product product = new Product();
			product.subject = str_subject;
			product.body = str_subject;
			product.price = str_money;

			String info;
			try {
				info = getNewOrderInfo(product);
				String sign = Rsa.sign(info, Keys.PRIVATE);
				sign = URLEncoder.encode(sign, "utf-8");
				info += "&sign=\"" + sign + "\"&" + getSignType();
				Log.i("ExternalPartner", "start pay");
				// start the pay.
				Log.i(TAG, "info = " + info);
				final String orderInfo = info;
				new Thread() {
					public void run() {
						AliPay alipay = new AliPay(ActivityRecharge.this,
								mHandler);

						// 设置为沙箱模式，不设置默认为线上环境
						// alipay.setSandBox(true);

						String result = alipay.pay(orderInfo);

						Log.i(TAG, "result = " + result);
						Message msg = new Message();
						msg.what = RQF_PAY;
						msg.obj = result;
						mHandler.sendMessage(msg);
					}
				}.start();
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	};

	private String getUserInfo() {
		String userId = "abs";
		return trustLogin(Keys.DEFAULT_PARTNER, userId);

	}

	private String trustLogin(String partnerId, String appUserId) {
		StringBuilder sb = new StringBuilder();
		sb.append("app_name=\"mc\"&biz_type=\"trust_login\"&partner=\"");
		sb.append(partnerId);
		Log.d("TAG", "UserID = " + appUserId);
		if (!TextUtils.isEmpty(appUserId)) {
			appUserId = appUserId.replace("\"", "");
			sb.append("\"&app_id=\"");
			sb.append(appUserId);
		}
		sb.append("\"");

		String info = sb.toString();

		// 请求信息签名
		String sign = Rsa.sign(info, Keys.PRIVATE);
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;

		return info;
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@Override
	public void requestFinish(JsonObject jsonObjectReturn) {

		List<Map<String, Object>> objList = getDataSource();

		this.list_gold.setAdapter(new GoldAdapter(getDataSource(), this));

	}

	private String getNewOrderInfo(Product product) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(getOutTradeNo());
		sb.append("\"&subject=\"");
		sb.append(product.subject);
		sb.append("\"&body=\"");
		sb.append(product.body);
		sb.append("\"&total_fee=\"");
		sb.append(product.price.replace("一口价:", ""));
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode(
				"http://pay.39du5.com/39/alipay/notify_url.php", "utf-8"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com", "utf-8"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String key = format.format(date);

		java.util.Random r = new java.util.Random();
		key += r.nextInt();
		key = key.substring(0, 15);
		Log.d(TAG, "outTradeNo: " + key);
		return key;
	}

	public static class Product {
		public String subject;
		public String body;
		public String price;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
			case RQF_LOGIN: {
				Toast.makeText(ActivityRecharge.this, result.getResultDesc(),
						Toast.LENGTH_SHORT).show();

			}
				break;
			default:
				break;
			}
		};
	};

	private class GoldAdapter extends BaseAdapter {

		private List<Map<String, Object>> data;
		private LayoutInflater inflater;
		private HashMap<Integer, View> lmap = new HashMap<Integer, View>();

		public GoldAdapter(List<Map<String, Object>> data, Context context) {

			this.data = data;
			this.inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO 自动生成的方法存根
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO 自动生成的方法存根
			return this.data.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO 自动生成的方法存根
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;

			if (lmap.get(position) == null) {
				convertView = this.inflater.inflate(R.layout.item_gold, null);

				holder = new ViewHolder();

				holder.btn = (Button) convertView.findViewById(R.id.btn_gold);
				holder.img = (ImageView) convertView
						.findViewById(R.id.img_gold);
				holder.txt = (TextView) convertView.findViewById(R.id.txt_gold);

				convertView.setTag(holder);

				lmap.put(position, convertView);

			} else {
				convertView = lmap.get(position);
				holder = (ViewHolder) convertView.getTag();
			}

			holder.btn.setText("￥"
					+ this.data.get(position).get("money").toString());

			holder.img.setImageResource((Integer) this.data.get(position).get(
					"img"));

			holder.txt.setText(data.get(position).get("gold").toString()
					+ "Hi币");

			holder.btn.setTag(this.data.get(position).get("money").toString());

			holder.btn.setOnClickListener(clickListener);

			return convertView;

		}

	}

	private static class ViewHolder {
		Button btn;
		TextView txt;
		ImageView img;
	}

	@Override
	protected void requestError() {
		// TODO 自动生成的方法存根

	}

}
